package br.com.californiahotel.client.viewControler.servico;

import java.math.BigDecimal;

import br.com.californiahotel.client.architecture.viewController.BasicController;
import br.com.californiahotel.client.interfaces.AsyncCallback;
import br.com.californiahotel.client.service.ServicoService;
import br.com.californiahotel.client.service.ServicoServiceAsync;
import br.com.californiahotel.client.viewControler.servico.ServicoFormView.Field;
import br.com.californiahotel.shared.models.Servico;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;

public class ServicoFormController extends BasicController {

	private final ServicoServiceAsync servicoService = GWT.create(ServicoService.class);

	public interface Display extends DisplayController {
		DynamicForm getForm();
	}

	public ServicoFormController(Display display) {
		super(display);
	}

	@Override
	protected void bind() {
		getItem(Field.SAVE).addClickHandler(saveButtonClickEvent());
	}

	private ClickHandler saveButtonClickEvent() {
		return new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Object value = getItem(Field.HIDDEN).getValue();
				Long parseLong = null;
				if(value != null){
					parseLong = Long.parseLong(value.toString());
				}
				servicoService.save(new Servico(parseLong, getItem(Field.DESCRIPTION).getDisplayValue(),getValueFromField(getItem(Field.VALUE))), new AsyncCallback<Boolean>() {

					@Override
					public void onSuccess(Boolean result) {
						if(result == true){
							SC.say("Servico salvo com sucesso");
						}else {
							SC.say("Falha");
						}
					}
				});
			}

			private BigDecimal getValueFromField(FormItem item) {
				String displayValue = item.getDisplayValue();
				return BigDecimal.valueOf(Double.parseDouble(displayValue.replace(",", ".")));
			}
		};
	}

	private Display getDisplay() {
		return ((Display)getDisplayController());
	}

	private FormItem getItem(Field value) {
		return getDisplay().getForm().getItem(value.getFieldName());
	}

}
